package com.recsmile.sgs;


import com.recsmile.sgs.core.net.codec.ProtoBufDecoder;
import com.recsmile.sgs.core.net.codec.ProtoBufEncoder;
import com.recsmile.sgs.net.codec.ServerChannelHandler;
import com.recsmile.sgs.util.CommandManager;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

/**
 * Created by hanyuanliang on 16/8/24.
 */
public class Server {
    public static void main(String[] args){
        CommandManager.load();
        ServerBootstrap serverBootstrap = new ServerBootstrap();

        EventLoopGroup boss = new NioEventLoopGroup(1);
        EventLoopGroup worker = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors() * 2);
        try {

            serverBootstrap.group(boss,worker).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0,4,0,4),
                            new ProtoBufDecoder(), new ProtoBufEncoder(),
                            new ServerChannelHandler());
                }
            }).option(ChannelOption.SO_KEEPALIVE,true);
            int port = 8899;
            ChannelFuture f = serverBootstrap.bind(port).sync();
            System.out.println("server start at:" + port);
            f.channel().closeFuture().sync();

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            worker.shutdownGracefully();
            boss.shutdownGracefully();
        }
    }
}
